﻿using ScriptBox.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ScriptBox
{
    /// <summary>
    /// SettingsWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsWindow : Window
    {
        public AppConfig CurrentConfig { get; private set; }
        private Key _lastKey;
        private ModifierKeys _modifiers;
        public SettingsWindow(AppConfig config)
        {
            InitializeComponent();
            // 创建新实例并复制属性值
            CurrentConfig = new AppConfig 
            {
                AutoHideEnabled = config.AutoHideEnabled,
                HotkeyModifiers = config.HotkeyModifiers,
                HotkeyKey = config.HotkeyKey
            };
            DataContext = CurrentConfig;
            UpdateHotkeyDisplay();
        }
        private void UpdateHotkeyDisplay()
        {
            if (CurrentConfig.HotkeyKey == 0)
            {
                txtHotkey.Text = "未设置";
                return;
            }

            // 转换修饰键
            var modifiers = new List<string>();
            if ((CurrentConfig.HotkeyModifiers & 0x0001) != 0) modifiers.Add("Alt");
            if ((CurrentConfig.HotkeyModifiers & 0x0002) != 0) modifiers.Add("Ctrl");
            if ((CurrentConfig.HotkeyModifiers & 0x0004) != 0) modifiers.Add("Shift");

            // 转换主键
            string keyName = CurrentConfig.HotkeyKey switch
            {
                0xC0 => "`",
                0x70 => "F1",
                0x31 => "1",
                _ => Enum.GetName(typeof(Key), KeyInterop.KeyFromVirtualKey(CurrentConfig.HotkeyKey)) ?? "未知键"
            };

            txtHotkey.Text = modifiers.Any() ?
                $"{string.Join(" + ", modifiers)} + {keyName}" :
                keyName;
        }

        // 添加Win32 API声明
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern short GetAsyncKeyState(int vKey);

        private void txtHotkey_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true; // 阻止默认输入处理
            
            _modifiers = Keyboard.Modifiers;
            // 特殊处理`键
            if ((GetAsyncKeyState(0xC0) & 0x8000) != 0) // 0xC0是`键的虚拟键码
            {
                _lastKey = Key.Oem3;
            }
            else
            {
                _lastKey = e.Key == Key.System ? e.SystemKey : e.Key;
            }

            // 过滤无效按键
            if (_lastKey == Key.LeftCtrl || 
                _lastKey == Key.RightCtrl ||
                _lastKey == Key.LeftAlt ||
                _lastKey == Key.RightAlt ||
                _lastKey == Key.LeftShift ||
                _lastKey == Key.RightShift)
            {
                return;
            }

            // 转换显示为可识别名称
            string keyName = _lastKey switch
            {
                Key.Oem3 => "`",
                _ => _lastKey.ToString()
            };

            // 转换按键显示
            txtHotkey.Text = $"{_modifiers} + {keyName}";

            // 转换虚拟键码（强制使用Win32检测结果）
            int vkCode = _lastKey == Key.Oem3 ? 0xC0 : KeyInterop.VirtualKeyFromKey(_lastKey);

            // 添加修饰键转换
            int modifiers = 0;
            if ((_modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) modifiers |= 0x0001;
            if ((_modifiers & ModifierKeys.Control) == ModifierKeys.Control) modifiers |= 0x0002;
            if ((_modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) modifiers |= 0x0004;

            CurrentConfig.HotkeyModifiers = modifiers; // 新增这行
            CurrentConfig.HotkeyKey = vkCode;
        }
        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            CurrentConfig.HotkeyModifiers = 0;
            CurrentConfig.HotkeyKey = 0;
            txtHotkey.Text = "未设置";
        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }
    }
}
